package com.digitalchina.lxnsy.toolkit;

import android.content.Context;
import android.os.Handler;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.digitalchina.lxnsy.R;

/**
 * ================================================
 * 项目名称：bigdata
 * 类描述：
 * 包名：com.digitalchina.bigdata.toolkit
 * 创建人：白彦东
 * 创建时间：2016/12/15 9:48
 * 修改备注：
 * ================================================
 */

public class ToastUtil {

    private static Toast mToast;
    public static final int duration = 2000;
    private static Handler mHandler = new Handler();
    private static Runnable r = new Runnable() {
        public void run() {
            mToast.cancel();
        }
    };

    public static void showToast(Context mContext, String text) {


        mHandler.removeCallbacks(r);
        if (mToast != null) {
            TextView tv = (TextView) mToast.getView().findViewById(R.id.view_toast_tv);
            tv.setText(text);
        } else
            mToast = newToast(mContext, text);
        mHandler.postDelayed(r, duration);
        mToast.show();
    }

    public static void showToast(Context mContext, int resId) {
        showToast(mContext, mContext.getResources().getString(resId));
    }


    /**
     * 返回自定义toast
     *
     * @param poContext
     * @param text
     * @return
     */
    public static Toast newToast(Context poContext, CharSequence text) {

        Toast result = new Toast(poContext);

        // 获取LayoutInflater对象
        LayoutInflater inflater = (LayoutInflater) poContext
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        // 由layout文件创建一个View对象
        View layout = inflater.inflate(R.layout.view_toast, null);

        // 实例化ImageView和TextView对象
        TextView textView = (TextView) layout.findViewById(R.id.view_toast_tv);
        textView.setText(text);

        result.setView(layout);
        result.setGravity(Gravity.BOTTOM, 0, Utils.dip2px(poContext, 70));
        result.setDuration(Toast.LENGTH_SHORT);

        return result;
    }

}
